//
//  NetWork.m
//  OnlineVideoEducation
//
//  Created by qiaofeng wu on 2018/2/23.
//  Copyright © 2018年 jiangwei. All rights reserved.
//

#import "NetWork.h"
#import <objc/runtime.h>
#import<CommonCrypto/CommonDigest.h>

#import "BaseTabBarVC.h"
//#import "HXLoginVC.h"
#import "NoEmptyTools.h"

@implementation NetWork

static bool isInternet = YES;

static NetWork *instance;

+ (instancetype)shareManager {
    if (instance == nil) {
        //1.实例化
        instance = [[NetWork alloc] initWithBaseURL:[NSURL URLWithString:baseURLString]];
        //2.可接受格式
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"image/jpeg", @"image/png", @"text/json", @"text/javascript", @"text/plain", nil];
        //4.超时
        instance.requestSerializer.timeoutInterval = 10.0;
    }
    return instance;
}

/** 自定义的 GET 请求 */
+ (void)GETWithUrlString:(NSString *)urlString
                  parmas:(NSDictionary *)params
           successBloock:(SuccessCompletedBlock)success
            failureBlock:(FailureCompletedBlock)failure {
    [SVProgressHUD show];
    [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkLoadingNotification object:@{@"Method":@"GET"}];
    [[NetWork shareManager] GET:urlString parameters:[self tokenDic:params] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkLoadingEndNotification object:@{@"Method":@"GET",@"isSuccess":@"1"}];
         [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkLoadingEndNotification object:@{@"Method":@"GET",@"isSuccess":@"0"}];
         [SVProgressHUD dismiss];
    }];
}

/** 自定义的 POST 请求 */
+ (void)POSTWithUrlString:(NSString *)urlString
                   parmas:(NSDictionary *)params
            successBloock:(SuccessCompletedBlock)success
             failureBlock:(FailureCompletedBlock)failure {
    [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkLoadingNotification object:@{@"Method":@"POST"}];
    [SVProgressHUD show];
    [[NetWork shareManager] POST:urlString parameters:[self tokenDic:params] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         [SVProgressHUD dismiss];
        [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkLoadingEndNotification object:@{@"Method":@"POST",@"isSuccess":@"1"}];
        responseObject = [NoEmptyTools noEmptyWithObject:responseObject];
  
        if ([responseObject[@"code"] integerValue] == 9999 || [responseObject[@"code"] integerValue] == 900) {
            
            //            [MBProgressHUD hideHUD];
            //
            //            @synchronized(self) {
            //
            //                jxt_showAlertTwoButton(@"请先登录", nil, @"取消", ^(NSInteger buttonIndex) {
            //
            //                    [UserModel outLog];
            //
            //                }, @"确定", ^(NSInteger buttonIndex) {
            //
            //                    __weak OVETabBarVC *VC = (OVETabBarVC *)[[UIApplication sharedApplication] keyWindow].rootViewController;
            //                    [VC presentViewController:[OVELoginVC new] animated:true completion:^{
            //                    }];
            //
            //                });
            //            }
            return;
        }
//        if ([responseObject[@"code"] integerValue] == 200) {
//            [JKToast showWithText:responseObject[@"message"]];
//        } else {
//            success(responseObject);
//        }
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
   
         [SVProgressHUD dismiss];
        [JKToast showWithText:NET_FAIL];
        [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkLoadingEndNotification object:@{@"Method":@"POST",@"isSuccess":@"0"}];
        if (!failure) { return; }
        failure(error);
    }];
    
}

+ (void)uploadUrl:(NSString *)url img:(NSArray *)imgs pramas:(NSDictionary *)prams successBloock:(SuccessCompletedBlock)success failureBlock:(FailureCompletedBlock)failure {
    [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkLoadingNotification object:@{@"Method":@"Upload"}];
     [SVProgressHUD show];
    [[NetWork shareManager] POST:url parameters:[self tokenDic:prams] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (UIImage *img in imgs) {
            NSData *imageData = UIImageJPEGRepresentation(img, 0.7);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
            [formData appendPartWithFileData:imageData name:@"picUrl" fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         [SVProgressHUD dismiss];
        success(responseObject);
        [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkLoadingEndNotification object:@{@"Method":@"Upload",@"isSuccess":@"1"}];
        NSLog(@">>>>请求成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
         [SVProgressHUD dismiss];
        [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkLoadingEndNotification object:@{@"Method":@"Upload",@"isSuccess":@"0"}];
        NSLog(@"艹艹艹艹艹艹 ===== 请求失败");
    }];
}

+ (NSDictionary *)tokenDic:(NSDictionary *)param {
    NSUserDefaults *user = [[NSUserDefaults alloc] init];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:param];
//    NSString *token = [user objectForKey:TokenKEY];
//    if (!token) { token = @""; }
//    [dic setObject:token forKey:TokenKEY];
//    [dic setObject:[self md5_32bit:@"haochen2018"] forKey:@"appsecret"];
    return dic;
}

#pragma mark -- 加密

+ (NSString *)sign {
    long timeStamp = (long)[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    NSMutableString *string = [NSMutableString string];
    [string appendString:[NSString stringWithFormat:@"%ld",timeStamp]];
    [string appendString:@"yyqb_dk*2#1@!"];
    NSString *sign = [NetWork sha1:string.copy];
    return sign;
}

//sha1加密方式
+ (NSString *)sha1:(NSString *)input {
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

// md5
+ (NSString *)md5_32bit:(NSString *)sourceString {
    if(!sourceString){
        return nil;//判断sourceString如果为空则直接返回nil。
    }
    //MD5加密都是通过C级别的函数来计算，所以需要将加密的字符串转换为C语言的字符串
    const char *cString = sourceString.UTF8String;
    //创建一个C语言的字符数组，用来接收加密结束之后的字符
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    //MD5计算（也就是加密）
    //第一个参数：需要加密的字符串
    //第二个参数：需要加密的字符串的长度
    //第三个参数：加密完成之后的字符串存储的地方
    CC_MD5(cString, (CC_LONG)strlen(cString), result);
    //将加密完成的字符拼接起来使用（16进制的）。
    //声明一个可变字符串类型，用来拼接转换好的字符
    NSMutableString *resultString = [[NSMutableString alloc]init];
    //遍历所有的result数组，取出所有的字符来拼接
    for (int i = 0;i < CC_MD5_DIGEST_LENGTH; i++) {
        [resultString  appendFormat:@"%02x",result[i]];
        //%02x：x 表示以十六进制形式输出，02 表示不足两位，前面补0输出；超出两位，不影响。当x小写的时候，返回的密文中的字母就是小写的，当X大写的时候返回的密文中的字母是大写的。
    }
    //打印最终需要的字符
    NSLog(@"resultString === %@",resultString);
    return resultString;
}

#pragma mark -- 检查网络状态

+ (BOOL)internet {
    return isInternet;
}

+ (void)checkNet {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    // 提示：要监控网络连接状态，必须要先调用单例的startMonitoring方法
    [manager startMonitoring];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == -1) {
            //            [MBProgressHUD showAutoMessage:@"未识别网络"];
            [JKToast showWithText:@"未识别网络"];
            isInternet = NO;
        }
        if (status == 0) {
            //            [MBProgressHUD showAutoMessage:@"未连接网络"];
            [JKToast showWithText:@"未连接网络"];
            isInternet = NO;
        }
        if (status == 1) {
            isInternet = YES;
        }
        if (status == 2) {
            isInternet = YES;
        }}];
}

@end
